package cn.oowoo.rabbitmq.simple;

import cn.oowoo.rabbitmq.config.RabbitConfig;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

/**
 * @Author ZhangBin
 * @Date 2021/5/8 13:48
 * @Description: 简单消息发送-生产者
 *  测试额外参数传递、消息过期时间等
 **/
public class SimpleProducer {

    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = RabbitConfig.createConnection();
        // 创建消息通道
        Channel channel = connection.createChannel();

        // 发送消息
        Map<String, Object> headers = new HashMap<>();
        headers.put("token", "11111111");

        AMQP.BasicProperties properties = new AMQP.BasicProperties.Builder()
                .deliveryMode(2)
                .contentEncoding("UTF-8")
                .headers(headers)
                .timestamp(new Date())
                .expiration("10000") //毫秒，如果没有消费者消费，超时消息将会被丢弃
                .messageId("123456789_UUID")
                .contentType("text/plain")
                .build();

        for(int i=0;i<10;i++){
            String msg =  "一条简单消息...." + i;

            channel.basicPublish(RabbitConfig.EXCHANGE_SIMPLE_NAME, RabbitConfig.ROUTING_SIMPLE_KEY, properties, msg.getBytes());
        }

        //消息发送完毕关闭信道，关闭链接
        channel.close();
        connection.close();
    }


    /*
    * 异常：
    *  com.rabbitmq.client.ShutdownSignalException: channel error; protocol method: #method<channel.close>(reply-code=404, reply-text=NOT_FOUND - no exchange 'SIMPLE_EXCHANGE' in vhost '/', class-id=60, method-id=40)
    *  第一次启动时先启动consumer，后启动provider。因为刚开始在mq中没有缓存的内容，第二次rabbitmq里面缓存了queue和exchange等信息就可以先启动provider了。
    *
    * */
}
